<!--购物车 -->
<template>
    <el-container class="cart">
      <el-header>
        <h1>Xmall 商城</h1>
        <h3>购物车</h3>
        <div class="search">
          <el-input
          placeholder="请输入内容"
          v-model="input"
          clearable
          width="100px" 
          @keypress.native.enter="searchByInput"
          >
        </el-input>
        <el-button plain width="20px" @click="searchByInput">搜索</el-button>
      </div>
      </el-header>
      <el-main>
        <div style="overflow:auto" class="content">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <span class="total">共有商品记录 {{total}} 条</span>
          <el-table
          v-infinite-scroll="load"
          infinite-scroll-disabled="disabled"
          :data="tableData"
          style="width: 100%">
          <el-table-column
            align ="center"
            prop ="id"
            width = "60"
          >
          <template slot-scope="scope">
            <el-checkbox-group v-model="checkedDataId" @change="handleCheckedCitiesChange">
              <el-checkbox :key="scope.row.id" :label="scope.row.id">{{""}}</el-checkbox>
            </el-checkbox-group>
          </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="商品图片">
            <template width="40" slot-scope="scope">
              <el-image :src="scope.row.imgList!=null&&scope.row.imgList.length>0?scope.row.imgList[0].url:null" style="width: 100px; height: 100px"></el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            label="商品名称"
            width="180">
          </el-table-column>
          <el-table-column
            label="单价"
            width="100">
            <template width="40" slot-scope="scope">
              {{'￥' + scope.row.price}}
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            width="200">
            <template slot-scope="scope">
              <el-input-number :min="0" size="small" v-model="scope.row.num" @change="(e,f) => amountChange(scope.$index, e, f)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            width="100"
            prop="sum">
            <!-- <template width="40" slot-scope="scope">
              {{'￥' + scope.row.price* scope.row.num}}
            </template> -->
          </el-table-column>
          <el-table-column label="操作">
            <template width="40" slot-scope="scope">
              <el-button type="danger" plain @click="deleteById(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
          <div class="tip">
            <span v-if="loading">加载中...</span>
            <span v-if="noMore">没有更多了</span>
          </div>
        </div>
      </el-main>
      <el-footer>
        <div class="display-div">
            <div class="left">
              <el-checkbox style="margin-right: 20px;" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              <el-link class="options" @click="deleteConfirm" :disabled="checkedDataId.length<=0">移除</el-link>
            </div>
            <div class="right options">
              <div style="margin-right: 100px;">已选择商品 <span>{{checkedCount}}</span> 件</div>
              <div> 合计：<span>{{totalMoney}}</span>  </div>
              <el-button class="button-pay" type="danger" style="margin-left: 10px" @click="settle">结 算</el-button>
            </div>
        </div>
      </el-footer>
    </el-container>
</template>

<script>
import qs from 'qs'
export default {
 name: 'Cart',
 data () {
  return {
    listQuery: {
      pageNum: 1,
      pageSize: 10,
      uid: ''
    },
    input: "",
    // 商品记录总数
    total: 0,
    // 总价
    totalMoney: 0,
    tableData: [],
    responseData: [],
    loading: false,
    checkAll: false,
    checkedDataId: [],
    isIndeterminate: true,
    checkedCount: 0
  };
 },
 created() {
   
   this.getList()
 },
 computed: {
    noMore () {
      return this.responseData.length == 0;
    },
    disabled () {
      return this.loading || this.noMore
    },
    
  },
 methods: {
    deleteConfirm() {
      if(this.checkedDataId.length > 0) {
        this.$confirm('确认将它们移出购物车?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteByIds()
          this.checkedDataId = [];
          // this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
                
        });
      }
    },
   getList() {
     this.listQuery.uid = sessionStorage.getItem("userId");
     this.listQuery.pageNum = 1;
     this.listQuery.pageSize = 10;
     console.log(this.listQuery.uid);
      this.axios.put('/api/cart', this.listQuery).then(response => {
        // console.log(response.data);
        this.tableData = [];
        if(response.data.code == 200) {
            this.responseData = response.data.data.content;
            console.log(this.responseData);
            this.tableData = this.responseData;
            console.log('tableData',this.tableData);
            this.total = response.data.data.totalSize;
            console.log('total',this.total);
        }
      }).catch(err => {
        console.log(err)
      })
   },
   load () {
      this.loading = true;
      this.listQuery.pageNum++;
      this.axios.put('/api/cart', this.listQuery).then(response => {
        //  console.log(response)
        if(response.data.code == 200) {
          this.responseData = response.data.data.content
          this.tableData = this.tableData.concat(this.responseData);
        }
      }).catch(err => {
        console.log(err)
      })
      this.loading = false;
    },
    amountChange(index, e, f) {
      let row = this.tableData[index];
      // e < f 减
      if(e < f) {
        this.tableData[index].sum -= row.price;
      }else{
        this.tableData[index].sum += row.price;
      }
      this.axios.post('/api/cart', {
        id: row.id,
        gid: row.gid,
        uid: this.listQuery.uid,
        num: e
      }).then(response => {
        if(response.data.code != 200) {
          this.error();
        } 
      } ).catch(error => {
        console.log(error);
      })
    },
    handleCheckAllChange(val) {
      this.totalMoney = 0;
      if(val) {
        this.checkedCount = this.tableData.length;
      }else {
        this.checkedCount = 0;
      }
      this.checkAll = val;
      this.isIndeterminate = !val;
      if(this.checkAll) {
        this.tableData.forEach(data => {
          this.totalMoney += data.sum;
          this.checkedDataId.push(data.id);
        });
      } else {
        this.checkedDataId = [];
      }
    },
    handleCheckedCitiesChange(value) {
      console.log(value);
      this.totalMoney = 0;
      value.forEach(e => {
        let sum = 0;
        for(let i of this.tableData){
          if(i.id === e){
            sum = i.sum;
            break;
          }
        }
        console.log(this.tableData);
        console.log(e);
        this.totalMoney += sum;
      })
      this.checkedCount = value.length;
      this.checkAll = this.checkedCount === this.tableData.length;
      this.isIndeterminate = this.checkedCount > 0 && this.checkedCount < this.tableData.length;
    },
    searchByInput() {
      let search = this.input.trim();
      if(search == "") {
        this.listQuery.pageNum = 1;
        this.getList();
        return;
      }
      this.axios.put('/api/cart', {
        pageNum: 1,
        pageSize: 10,
        uid: 1,
        name: search
        
      }).then(response => {
        if(response.data.code == 200) {
            this.responseData = response.data.data.content
            this.tableData = this.responseData;
            this.total = response.data.data.totalSize;
        } else {
          this.error();
        }
      }).catch(err => {
        console.log(err)
      })
    },
    deleteByIds() {
      var data = {
        ids: this.checkedDataId
      }
      var params = qs.stringify(data, { indices: false })
      this.axios.delete('/api/cart?'+params
      ).then(response => {
        if(response.data.code == 200) {
          this.getList();
        } else {
          this.error();
        }
      }).catch(err => {
        console.log(err)
      })
    },
    deleteById(id) {
      console.log(id)
      this.axios.delete('/api/cart', {
        params:{
          ids: id
        }
      }).then(response => {
        // console.log(response);
        if(response.data.code == 200) {
          this.getList();
        } else {
          this.error();
        }
      }).catch(err => {
        console.log(err)
      })
    },
    settle() {
      this.checkedData = [];
      this.tableData.forEach(e =>  {
        if(this.checkedDataId.indexOf(e.id) > -1) {
          this.checkedData.push(e);
        }
      })  
      this.$store.commit("settle", {
        idList: this.checkedDataId,
        dataList: this.checkedData,
        totalMoney: this.totalMoney
      });
      this.$router.push({
        path: '/cart/pay',
      })
    },

    error() {
      this.$message({
        message: '出错了T-T',
        type: 'error',
        center: true
      });
    }
 }
}

</script>
<style scoped>
.cart {
  padding-top: 60px;
  overflow-x: hidden;
}
.el-container {
  height: 100%;
  margin: 0 10%;
}
.content {
  height: 485px;
}
.tip {
  padding: 20px 0;
  text-align: center;
  color: #666;
}
.el-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 0 10%;
  line-height: 60px;
  background-color: #fff;
}
h1, h3 {
  float: left;
}
h3 {
  line-height: 42px;
  margin-left: 16px;
}
.search {
  float: right;
  width: 300px;
  height: 72px;
  line-height: 72px;
}
.search > .el-input {
  display: inline-block;
  width: 70%;
}
.search > .el-button {
  display: inline-block;
  width: 30%;
}
.total {
  font-size: 14px;
  margin-left: 50px;
}
.el-footer .display-div div {
  display: inline-block;
}
.left {
  float: left;
}
.right {
  float: right;
}
.options {
  padding: 0 20px;
  font-size: 14px;
  line-height: 61px;
  color: #666;
}
.options span {
  color: red;
  font-weight: 700;
  font-size: 16px;
}
.button-pay {
  height: 60px;
  font-size: 20px;
  color: #fff;
  padding: 0 40px;
}
</style>